import React, { useState, useRef, useEffect } from 'react'
import { Link } from 'react-router-dom'
import { useSelector } from 'react-redux'
import InfiniteScroll from "react-infinite-scroller";
import { Loading, RatingStar } from 'src/components'
import { CSSTransition } from 'react-transition-group';
import { imgBaseUrl } from 'src/config/env'
import { shopList } from 'src/api/getData'
import { showBack, animate } from 'src/config/mUtils'
import './index.scss'
import classNames from 'classnames';

const ShopList = (props) => {
    const {
        restaurantCategoryId,
        restaurantCategoryIds,
        sortByType,
        deliveryMode,
        supportIds,
        // confirmSelect,
        scrollParentRef
    } = props
    const { latitude, longitude, geohash } = useSelector((state) => state)
    const [offset, setOffset] = useState(0)
    const [shopListArr, setShopListArr] = useState([])
    const [preventRepeatReuqest, setPreventRepeatReuqest] = useState(false)
    const [showBackStatus, setShowBackStatus] = useState(false)
    const [showLoading, setShowLoading] = useState(true)
    const [touchend, setTouchend] = useState(false)

    const ref = useRef();


    useEffect(() => {
        // msite页面
        if (latitude && longitude) {
            //获取数据
            shopList(latitude, longitude, 0, restaurantCategoryId).then((res) => {
                setShopListArr(res.data.list)
                if (res.data.list.length < 20) {
                    setTouchend(true)
                }
                setShowLoading(false)
                //开始监听scrollTop的值，达到一定程度后显示返回顶部按钮
                showBack(status => {
                    setShowBackStatus(status)
                });
            })
        }
    }, [latitude, longitude, restaurantCategoryId])


    //到达底部加载更多数据
    const loadMore = () => {
        if (touchend) {
            return
        }
        //防止重复请求
        if (preventRepeatReuqest) {
            return
        }
        setShowLoading(true)
        setPreventRepeatReuqest(true)
        let offsetNew = offset + 20
        setOffset(offsetNew) //数据的定位加20位
        shopList(latitude, longitude, offsetNew, restaurantCategoryId).then(res => {
            setShowLoading(false)
            setShopListArr([...shopListArr, ...res])
            //当获取数据小于20，说明没有更多数据，不需要再次请求数据
            if (res.length < 20) {
                setTouchend(true)
                return
            }
            setPreventRepeatReuqest(false)
        })
    }

    //返回顶部
    const backTop = () => {
        animate(document.body, { scrollTop: '0' }, 400, 'ease-out');
    }

    useEffect(() => {
        //监听父级传来的数据发生变化时，触发此函数重新根据属性值获取数据
        if (latitude && longitude && restaurantCategoryIds && sortByType && deliveryMode && supportIds) {
            setShowLoading(true)
            setOffset(0)
            shopList(latitude, longitude, 0, '', restaurantCategoryIds, sortByType, deliveryMode, supportIds).then(res => {
                setShowLoading(false)
                setShopListArr(res)
            })
        }
    }, [latitude, longitude, restaurantCategoryIds, sortByType, deliveryMode, supportIds])

    const zhunshi = (supports) => {
        let zhunStatus;
        if ((supports instanceof Array) && supports.length) {
            supports.forEach(item => {
                if (item.icon_name === '准') {
                    zhunStatus = true;
                }
            })
        } else {
            zhunStatus = false;
        }
        return zhunStatus
    }

    return <div className="component_shoplist">
        <InfiniteScroll
            initialLoad={false}
            pageStart={1}
            loadMore={loadMore}
            hasMore={!touchend}
            useWindow={false}
            getScrollParent={() => scrollParentRef.current}
        >
            {
                shopListArr.length > 0 ? <ul type="1">
                    {
                        shopListArr.map(item => {
                            return <li
                                className="shop_li"
                                key={item.id}
                            >
                                <Link to={`/shop?geohash=${geohash}&id=${item.id}`} >
                                    <section>
                                        <img src={`${imgBaseUrl}${item.image_path}`} className="shop_img" alt="" />
                                    </section>
                                    <hgroup className="shop_right">
                                        <header className="shop_detail_header">
                                            <h4 className={classNames('shop_title ellipsis', {
                                                'premium': item.is_premium
                                            })}
                                            >{item.name}</h4>
                                            <ul className="shop_detail_ul">
                                                {
                                                    item.supports && item.supports.map(item => {
                                                        return <li key={item.id} className="supports">{item.icon_name}</li>
                                                    })
                                                }
                                            </ul>
                                        </header>
                                        <h5 className="rating_order_num">
                                            <section className="rating_order_num_left">
                                                <section className="rating_section">
                                                    <RatingStar rating={item.rating}></RatingStar>
                                                    <span className="rating_num">{item.rating}</span>
                                                </section>
                                                <section className="order_section">
                                                    月售{item.recent_order_num}单
                                                </section>
                                            </section>
                                            <section className="rating_order_num_right">
                                                {
                                                    item.delivery_mode && <span className="delivery_style delivery_left">{item.delivery_mode.text}</span>
                                                }
                                                {
                                                    zhunshi(item.supports) && <span className="delivery_style delivery_right">准时达</span>
                                                }
                                            </section>
                                        </h5>
                                        <h5 className="fee_distance">
                                            <p className="fee">
                                                ¥{item.float_minimum_order_amount}起送
                                                <span className="segmentation">/</span>
                                                {item.piecewise_agent_fee.tips}
                                            </p>
                                            <p className="distance_time">
                                                {
                                                    Number(item.distance) ? <span>{item.distance > 1000 ? (item.distance / 1000).toFixed(2) + 'km' : item.distance + 'm'}
                                                        <span className="segmentation">/</span>
                                                    </span> : <span >{item.distance}</span>
                                                }
                                                <span className="segmentation">/</span>
                                                <span className="order_time">{item.order_lead_time}</span>
                                            </p>
                                        </h5>
                                    </hgroup>
                                </Link></li>
                        })
                    }
                </ul> : <ul className="animation_opactiy">
                    {
                        [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map(item => {
                            return <li className="list_back_li" key={item}>
                                <img src="/images/shopback.svg" className="list_back_svg" alt="" />
                            </li>
                        })
                    }
                </ul>
            }
        </InfiniteScroll>
        {showBackStatus && <aside className="return_top" onClick={backTop}>
            <svg className="back_top_svg">
                <use xmlnsXlink="http://www.w3.org/1999/xlink" xlinkHref="#backtop"></use>
            </svg>
        </aside>}
        {
            touchend && <p className="empty_data">没有更多了</p>
        }
        <div ref={ref} style={{
            backgroundColor: 'red'
        }}></div>

        <CSSTransition in={showLoading} classNames="loading" timeout={500} unmountOnExit>
            <Loading />
        </CSSTransition>
    </div>
}

export default ShopList